package com.lk.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lk.web.entity.SysPermission;
import com.lk.web.entity.SysRole;
import com.lk.web.mapper.SysPermissionMapper;
import com.lk.web.mapper.SysRoleMapper;
import com.lk.web.service.SysRoleService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 角色表 服务实现类
 *
 * @author Aspirin
 * @since 2020-06-21
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
    implements SysRoleService {
  @Override
  public Page<SysRole> selectPage(Page<SysRole> page, SysRole sysRole) {
    return baseMapper.customSelectPage(page, sysRole);
  }

  @Override
  public Page<SysRole> selectPage2(Page<SysRole> page, LambdaQueryWrapper<SysRole> qw) {
    return baseMapper.selectPage(page, qw);
  }

  @Autowired private SysPermissionMapper sysPermissionMapper;

  @Override
  public SysRole findById(Long id) {
    if (id == null) {
      // 返回一个空对象，防止前端页面 报错
      return new SysRole();
    }
    // 1. 通过角色id查询对应的角色信息
    SysRole sysRole = baseMapper.selectById(id);
    // 2. 通过角色id查询所拥有的权限
    List<SysPermission> permissions = sysPermissionMapper.findByRoleId(id);
    // 3. 将查询到的权限set到角色对象中SysRole
    sysRole.setPerList(permissions);
    return sysRole;
  }

  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  @Override
  public boolean saveOrUpdate(SysRole entity) {
    entity.setUpdateDate(LocalDateTime.now());
    // 1. 更新角色表中的数据
    boolean flag = super.saveOrUpdate(entity);

    if (flag) {
      // 2. 更新角色权限关系表中的数据(删除)
      baseMapper.deleteRolePermissionByRoleId(entity.getId());

      // 2. 新增角色权限关系表中的数据
      if (CollectionUtils.isNotEmpty(entity.getPerIds())) {
        baseMapper.saveRolePermission(entity.getId(), entity.getPerIds());
      }
    }
    return flag;
  }

  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  @Override
  public boolean deleteById(Long id) {
    // 1. 通过id删除角色信息表数据
    baseMapper.deleteById(id);
    // 2. 通过id删除角色权限关系表数据
    baseMapper.deleteRolePermissionByRoleId(id);
    return true;
  }
}
